<template>
    <div :class="['container', hasType ? 'has-type' : '']">
        <div class="chart-search"></div>
        <div class="chart-content">
            <div :id="container" class="chart-views"></div>
        </div>
    </div>
</template>
<script>
import Highcharts from 'highcharts';
import { formatData, formatStringToTime } from '@/common/js/chartsFormat.js'
import { dateFormatter, deepAssign, formatterNumber } from '@/common/js/util.js'
export default {
    props: ['dataArr', 'container', 'hasType', '_particleSize'],
    data() {
        return {
            charts: null,
            particleSize: 'day',       // 粒度
        }
    },
    created() {
        this.particleSize = this._particleSize || 'day';
    },
    methods: {
        chartInit(dataArr = null) {
            const that = this
            dataArr = deepAssign({}, dataArr);
            if(this.particleSize != 'sort' && this.particleSize != 'sortDay') {
                dataArr.series = dataArr.series.map(item => {
                    item.data = formatData(item.data, this.particleSize)
                    return item;
                })
            }
            // 设置千分分隔符为 ','
            Highcharts.setOptions({
                lang: { thousandsSep: ',' } 
            })
            this.charts = Highcharts.chart(this.container, {
                chart: {
                    type: dataArr.type || 'bar', 
                }, 
                title: false,
                credits: { enabled: false },  // 去版权水印
                exporting: { enabled: false }, // 隐藏导出
                yAxis: Object.assign({
                    title: null,
                    lineWidth: 1,
                    tickLength: 5, // 刻度线长度
                    gridLineWidth: 0,
                    tickWidth: 1,
                    maxPadding: 0.1, // 相对于轴长的最大填充，当最大值出现在接近边缘时或者超边，设置此参数可以有效调整
                    minRange: 9, // 最小范围
                    min: 0, // 最小刻度值
                    allowDecimals: false, // 禁止出现小数
                }, dataArr.yAxis || {}),
                xAxis: deepAssign({
                    type: that.particleSize == 'day' ? 'datetime' : 'category',
                    lineWidth: 0,
                    labels: {
                        y: 22,
                        formatter: function() {
                            if(this.axis.options.type == 'datetime') {
                                return dateFormatter(dataArr.labelFormat || "YYYYMMDD", this.value) // 标签格式化，针对缩小时日期变为英文格式
                            } else if(that.particleSize == 'sortDay') {
                                return dateFormatter("MM-DD", formatStringToTime(this.value)) // 标签格式化，针对缩小时日期变为英文格式
                            }
                            return this.value
                        }
                    },
                    //lineColor: '#e3e3e3', // 轴线颜色
                    //tickColor: '#e3e3e3', // 轴刻度线颜色
                    tickWidth: 1,
                    tickmarkPlacement: 'on',
                    tickLength: 5, // 刻度线长度
                    tickPositioner: function (min, max) {
                        const interval = this.options.type == 'datetime' ? 24 * 3600 * 1000 : 1;
			        	const diff = (this.dataMax - this.dataMin) / (interval), width = this.width;
                        const tickAmount = dataArr.labelFormat == 'MM-DD' ? 15 : 10
                        let step = Math.floor(width * tickAmount / 1080); // 根据宽度自动调整 步阶(width = 1080px 可以放 10 个刻度)
                        if(step > diff) {
                            step = diff
                        }
                        var positions = [],
			        		tick = Math.floor(this.dataMin),
			        		increment = Math.ceil(diff / step) * interval; // 增量
			        	for (tick; tick - increment < this.dataMax; tick += increment) {
                            // if(tick < this.dataMax && (tick + increment) > this.dataMax) {
                            if(tick + increment > this.dataMax) {
                                tick = this.dataMax;
                            }
			        		positions.push(tick);
			        	}
                        if(positions.length < 1) positions = [0] // 当min = max = 0的情况下，需默认给出一个初始值
			        	return positions;
			        },
                }, dataArr.xAxis || {}),
                tooltip: {
                    enabled: dataArr.tooltip === false ? false : true, // 隐藏提示框
                    shared: true,
                    borderRadius: 6,
                    borderWidth: 0,
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    useHTML: true,
                    formatter: function() {
                        // const value = this.points[0].point.series.xAxis.options.type == 'datetime' ? dateFormatter("YYYYMMDD", this.x) : this.points[0].key;
                        // const valueSuffix = dataArr.valueSuffix || '';
                        // let _color
                        // if(dataArr.type == "column") {
                        //     _color = this.points[0].color.stops[0][1]
                        // } else {
                        //     _color = this.points[0].color.stops[1][1]
                        // }
                        // return `<small style="margin-bottom:5px;display:block">${value}</small><span style="color:${_color};font-size:14px">●</span> ${this.points[0].series.name}: ${formatterNumber(this.y, 100000, 2, true)}${valueSuffix}<br/>`
                        let html = '', _color = ''
                        let valueSuffix = dataArr.valueSuffix || '';
                        this.points.forEach(point => {
                            const value = this.points[0].point.series.xAxis.options.type == 'datetime' ? dateFormatter("YYYYMMDD", this.x) : this.points[0].key;
                            if(dataArr.type == "column") {
                                _color = point.color.stops[0][1]
                            } else {
                                _color = point.color.stops[1][1]
                            }
                            if (point.series.tooltipOptions.valueSuffix) {
                                valueSuffix = point.series.tooltipOptions.valueSuffix
                            }
                            if (!html) html = `<small style="margin-bottom:5px;display:block">${value}</small><span style="color:${_color};font-size:14px">●</span> ${point.series.name}: ${formatterNumber(point.y, 100000, 2, true)}${valueSuffix}<br/>`
                            else html += `<span style="color:${_color};font-size:14px">●</span> ${point.series.name}: ${formatterNumber(point.y, 100000, 2, true)}${valueSuffix}<br/>` 
                        })
                        return html 
                    },
                    padding: 12
                },
                legend: Object.assign({
                    enabled: false, // 隐藏图例
                    itemDistance: 40,  // 图例项间距
                    verticalAlign: 'top',
                    squareSymbol: false,
                    symbolWidth: 20,
                    symbolY: 5,
                    symbolRadius: 1,
                    symbolPadding: 7,
                }, dataArr.legend || {}),
                plotOptions: {
                    bar: {
                        borderWidth: 0,
                        dataLabels: {
                            enabled: true,
                            formatter: function() {
                                return dataArr.formatter?.call(this, dataArr.total);
                            },
                            style: {
                                'fontWeight': 'normal'
                            },
                            x: 5, // 偏移，指和柱形右侧边缘的距离
                        },
                        pointPadding: 0, // 设置2根柱状之间的间距，默认 0.1
                        pointWidth: dataArr.pointWidth || undefined, // 柱状宽度
                    },
                    column: Object.assign({
                        borderWidth: 0,
                        maxPointWidth: 40, // 柱形最大宽度
                        minPointLength: 2,// 防止落差太大，小数据设置最小显示2个长度
                        dataLabels: {
                            enabled: dataArr.dataLabels || false,
                            formatter: function() {
                                if(that.particleSize == "sort") {
                                    if(this.y > 0) return formatterNumber(this.y, 10000, 2, true)
                                    else return ''
                                } else {
                                    return formatterNumber(this.y, 10000, 2, true)
                                }
                            },
                            color: '#666',
                            style: {
                                'fontWeight': 'normal',
                                'textOutline' : 'none',
                            },
                        },
                    }, dataArr.plotOptions && dataArr.plotOptions.column || {}),
                },
                series: dataArr.series
            })
        },
        updateChart(val) {
            this.charts.update({
                series: val
            })
        }
    },
    watch: {
        'dataArr.series': function(val, oldVal) {
            //if(!this.charts || this.dataArr.init) {
                this.chartInit(this.dataArr)
            //} else {
            //    this.updateChart(val);
            //}
        }
    }
}
</script>
<style lang="scss" scoped>
    .container, .chart-views{
        width: 100%;
        height: 100%;
    }
    .chart-search {
        position:relative;
        height: 10px;
    }
    .chart-content {
        box-sizing: border-box;
        width: 100%;
        height: calc(100% - 12px);
        padding: 0px 0 20px;
    }
    .has-type {
        .chart-search { height: 62px; }
        .chart-content { height: calc(100% - 62px); }
    }
    /deep/.highcharts-halo.highcharts-color-undefined{
        fill: transparent; // 清除标记点 阴影背景
    }
    /deep/.highcharts-legend-item .highcharts-point {
        y: 5
    }
</style>